package org.dromara.web.service;


import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;
import java.util.function.Consumer;

/**
 *  分布式锁操作类
 *
 */
@Service
public class RLockService {

    @Autowired
    RedissonClient redissonClient;


    static final String lock_user_wallet = "redis_lock_user_wallet_%s";


    public void lock(String lockName, Consumer<RLock> consumer) {
        RLock lock = redissonClient.getLock(lockName);
        try {
            boolean isLock = lock.tryLock(1, 15, TimeUnit.SECONDS);
            if (isLock) {
                consumer.accept(lock);
            } else {
                throw new RuntimeException("账户异常");
            }
        } catch (InterruptedException e) {

        } finally {
            if (lock.isHeldByCurrentThread()) {
                lock.unlock();
            }
        }
    }


    /**
     * 锁定用户钱包
     *
     * @param userid
     * @param consumer
     */
    public void lockUserWallet(Long userid, Consumer<RLock> consumer) {
        lock(String.format(lock_user_wallet, userid), consumer);
    }

}
